package com.example.roam.ui.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.roam.R;
import com.example.roam.api.Api;
import com.example.roam.model.gson.Forum;
import com.example.roam.model.gson.ForumOffice;
import com.example.roam.model.gson.ForumSearch;
import com.example.roam.model.gson.Histories;
import com.example.roam.ui.adpter.ForumNormalAdapter;
import com.example.roam.ui.adpter.ForumSearchAdapter;
import com.example.roam.ui.adpter.RecommendAdapter;
import com.example.roam.utils.HttpUtil;
import com.example.roam.utils.JsonCacheUtil;
import com.example.roam.utils.KeyboardUtil;
import com.example.roam.utils.LogUtils;
import com.example.roam.utils.StatusBarUtils;
import com.example.roam.view.TextFlowLayout;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class SearchActivity extends AppCompatActivity {
    private ImageView left , imgDrop;
    private EditText edtSearch;
    private ImageView searchDropBtn;
    private TextFlowLayout historyTextFlowLayout;
    private TextView btn_cancel;
    private GridView gridViewRecommend;
    private RecommendAdapter recommendAdapter;
    private ForumSearchAdapter forumSearchAdapter;
    private RelativeLayout historyContainer;
    private LinearLayout recommendContainer;
    private int currentPage = 0;
    private String currentKeyWord = "";
    private FrameLayout frameLayout;
    private State currentState = State.NONE;
    private View errorView;
    private View loadingView;
    private View successView;
    private View emptyView;
    private View noneView;
    private ListView searchList;
    private TwinklingRefreshLayout search_list_container;
    private static final String KEY = "hty";
    private JsonCacheUtil jsonCacheUtil;

    public enum State{
        LOADING,ERROR,SUCCESS,EMPTY,NONE;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        StatusBarUtils.setWindowStatusBarColor(this, R.color.purple_500);//设置状态栏颜色为银白色

        frameLayout = this.findViewById(R.id.base_container);
        loadStateView(); // 给framLayout加载各种view
        // successView下的控件
        search_list_container = successView.findViewById(R.id.search_list_container);
        searchList = successView.findViewById(R.id.search_list);
        forumSearchAdapter = new ForumSearchAdapter(this);
        initView();
        initData();
        initEvent();
    }

    public void initView(){
        left = this.findViewById(R.id.left);
        imgDrop = this.findViewById(R.id.img_drop);
        edtSearch = this.findViewById(R.id.edt_search);
        searchDropBtn = this.findViewById(R.id.search_drop_btn); // x
        historyTextFlowLayout = this.findViewById(R.id.history_text_flow_layout);
        historyContainer = this.findViewById(R.id.history_container);
        btn_cancel = this.findViewById(R.id.btn_cancel);
        gridViewRecommend = this.findViewById(R.id.gridview_recommend);
        recommendContainer = this.findViewById(R.id.recommend_container);
        recommendAdapter = new RecommendAdapter(this);
        jsonCacheUtil = JsonCacheUtil.getInstance();

    }

    public void loadStateView(){
        errorView = LayoutInflater.from(this).inflate(R.layout.activity_error,null,false);
        frameLayout.addView(errorView);
        loadingView = LayoutInflater.from(this).inflate(R.layout.activity_loading,null,false);
        frameLayout.addView(loadingView);
        successView = LayoutInflater.from(this).inflate(R.layout.search_success,null,false);
        frameLayout.addView(successView);
        emptyView = LayoutInflater.from(this).inflate(R.layout.activity_empty,null,false);
        frameLayout.addView(emptyView);
        noneView = LayoutInflater.from(this).inflate(R.layout.activity_none,null,false);
        frameLayout.addView(noneView);
        setState(State.NONE);
    }

    public void setState(State state) {
        this.currentState = state;
        if (currentState == state.SUCCESS) {
            successView.setVisibility(View.VISIBLE);
        } else {
            successView.setVisibility(View.GONE);
        }
        if (currentState == State.LOADING) {
            loadingView.setVisibility(View.VISIBLE);
        } else {
            loadingView.setVisibility(View.GONE);
        }
        if (currentState == State.ERROR) {
            if( currentPage > 0 ){ currentPage -= 10;}
            errorView.setVisibility(View.VISIBLE);
        } else {
            errorView.setVisibility(View.GONE);
        }
        if(currentState == State.EMPTY){
            emptyView.setVisibility(View.VISIBLE);
        }else {
            emptyView.setVisibility(View.GONE);
        }
        if(currentState == State.NONE){
            noneView.setVisibility(View.VISIBLE);
        }else {
            noneView.setVisibility(View.GONE);
        }
    }


    public void initData() {
        JsonCacheUtil instance = JsonCacheUtil.getInstance();
        Histories histories = instance.getValue(KEY, Histories.class);
        if (histories != null) {
            historyTextFlowLayout.setTextList(histories.getHistoryArray());
        }
        gridViewRecommend.setAdapter(recommendAdapter);
        ArrayList<String> recommendArray = new ArrayList<>();
        recommendArray.add("青城山");
        recommendArray.add("都江堰");
        recommendArray.add("乐山大佛");
        recommendArray.add("剑门关");
        recommendArray.add("峨眉山");
        recommendArray.add("九寨沟");
        recommendAdapter.setDataArray(recommendArray);
        searchList.setAdapter(forumSearchAdapter);
        search_list_container.setEnableRefresh(false);
        search_list_container.setEnableLoadmore(true);
    }

    public void initEvent(){

        //下拉刷新事件
        search_list_container.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                doMoreSearch();
            }
        });

        // 回退页面事件
        left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SearchActivity.this,ForumActivity.class);
                startActivity(intent);
                SearchActivity.this.finish();
            }
        });

        // searchEdt删除事件
        searchDropBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edtSearch.setText("");
                edtSearch.clearFocus();
            }
        });

        /** 搜索事件，输入后点击键盘搜索  */
        edtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if( actionId == EditorInfo.IME_ACTION_SEARCH ){
                    doSearch();
                }
                return false;
            }
        });

        // 点击历史记录事件
        historyTextFlowLayout.setOnFlowTextItemClickListener(new TextFlowLayout.OnFlowTextItemClickListener() {
            @Override
            public void onFlowItemClick(String text) {
                edtSearch.setText(text.replace("#",""));
                doSearch();
            }
        });

        // 历史删除事件
        imgDrop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                delCache();
            }
        });

        // 取消事件
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                KeyboardUtil.hideKeyboard(SearchActivity.this,edtSearch);
                edtSearch.setText("");
                edtSearch.clearFocus();
                showSearchView(false);
            }
        });

        // searchEdt文本变化事件
        edtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String keyword = s.toString().trim();
                if( keyword != null &&  keyword.length() > 0 ){
                    searchDropBtn.setVisibility(View.VISIBLE);
                }else {
                    searchDropBtn.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        // 推荐子项事件
        gridViewRecommend.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                edtSearch.setText(recommendAdapter.getDataArray().get(position).replace("#",""));
                doSearch();
            }
        });

        //
//        searchList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                initForumHtmlNet(forumSearchAdapter.getDataArray().get(position).getScenicReleaseInfo().getScenicReleaseId());
//            }
//        });
    }

    private void saveSearch(){ //保存历史记录
        Histories histories = jsonCacheUtil.getValue(KEY, Histories.class);
        List<String> historyArray = null;
        if( histories == null ){
            histories = new Histories();
            historyArray = new ArrayList<>();
            histories.setHistoryArray(historyArray);
        }else {
            historyArray = histories.getHistoryArray();
        }

        if (historyArray.contains(currentKeyWord)) {
            historyArray.remove(currentKeyWord);
        }
        historyArray.add(currentKeyWord);
        jsonCacheUtil.saveCacheWithDuration(KEY,histories,1000*60*24*5); // 默认五天存粹时间
        if( historyArray.size() > 10 ){         // 对个数限制
            historyArray = historyArray.subList(0,10); // 大于10就剪切
        }
        historyTextFlowLayout.setTextList(historyArray);
    }

    private void delCache(){ // 删除历史记录，历史面板隐藏
        JsonCacheUtil jsonCacheUtil = JsonCacheUtil.getInstance();
        jsonCacheUtil.delCache(KEY);
        historyContainer.setVisibility(View.GONE);
    }

    private void doSearch(){
        currentPage = 0;
        currentKeyWord = edtSearch.getText().toString().trim();
        showSearchView(true);
        setState(State.LOADING);
        saveSearch();
        Retrofit retrofit = new Retrofit.Builder().baseUrl(HttpUtil.ADDRESS).addConverterFactory(GsonConverterFactory.create()).build();
        retrofit.create(Api.class).findAllByTagText(currentKeyWord,currentPage,HttpUtil.COOKIE).enqueue(new Callback<ForumSearch>() {
            @Override
            public void onResponse(Call<ForumSearch> call, Response<ForumSearch> response) {
                // 隐藏历史和推荐 显示ListView
                int code = response.code();
                if( code == 200 ){
                    ForumSearch forumSearch = response.body();
                    List<ForumSearch.ScenicWithPageList> scenicWithPageList = forumSearch.getData().getScenicWithPageList();
                    if(scenicWithPageList!=null && scenicWithPageList.size() >0 ) {
                        forumSearchAdapter.setData(scenicWithPageList);
                        setState(State.SUCCESS);
                        LogUtils.i(SearchActivity.class,forumSearch.getData().getScenicWithPageList().toString());
                    }else {
                        setState(State.EMPTY);
                    }

                }else {
                    LogUtils.i(SearchActivity.class,"服务器出错！");
                    setState(State.ERROR);
                }
            }

            @Override
            public void onFailure(Call<ForumSearch> call, Throwable t) {
                t.printStackTrace();
                setState(State.ERROR);
            }
        });
    }

    private void doMoreSearch(){
        currentPage += 5;
        currentKeyWord = edtSearch.getText().toString().trim();
        showSearchView(true);  // 隐藏历史和推荐 显示ListView
        saveSearch();  //保存历史记录
        Retrofit retrofit = new Retrofit.Builder().baseUrl(HttpUtil.ADDRESS).addConverterFactory(GsonConverterFactory.create()).build();
        retrofit.create(Api.class).findAllByTagText(currentKeyWord,currentPage,HttpUtil.COOKIE).enqueue(new Callback<ForumSearch>() {
            @Override
            public void onResponse(Call<ForumSearch> call, Response<ForumSearch> response) {
                int code = response.code();
                ForumSearch forumSearch = response.body();
                if( code == 200 && forumSearch.getData().getScenicWithPageList() != null){
                    forumSearchAdapter.setMoreData(forumSearch.getData().getScenicWithPageList());
                    LogUtils.i(SearchActivity.class,forumSearch.toString());
                    loadMoreSuccess();
                }else {
                    showNoMoreData();
                    loadMoreSuccess();
                }
            }

            @Override
            public void onFailure(Call<ForumSearch> call, Throwable t) {
                t.printStackTrace();
                setState(State.ERROR);
            }
        });
    }

    public void showSearchView( boolean isVisible) {
        if (isVisible) {
            recommendContainer.setVisibility(View.GONE);
            historyContainer.setVisibility(View.GONE);
            frameLayout.setVisibility(View.VISIBLE);
        }else {
            recommendContainer.setVisibility(View.VISIBLE);
            historyContainer.setVisibility(View.VISIBLE);
            frameLayout.setVisibility(View.GONE);
        }
    }

    public void loadMoreSuccess(){
        search_list_container.finishLoadmore();
    }

    public void showNoMoreData(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(SearchActivity.this,"没有更多数据了...",Toast.LENGTH_SHORT).show();
            }
        });
    }

//    public void initForumHtmlNet(int srid){
//        Intent intent = new Intent(this, WebActivity.class);
//        intent.putExtra("url",HttpUtil.ADDRESS+"getView/getScenicReleaseView/"+srid);
////        intent.putExtra("url",HttpUtil.ADDRESS+"getView/getScenicReleaseView/"+srid);
//        startActivity(intent);
//    }
}